<template>
  <v-page edit :footer="{ offset: 10 }">
    <Anchors v-if="isLook" class="fixed right-4 top-24" style="width: 199px;margin-top: -2px;" />
    <div :class="isLook && 'pr-52'">
      <el-form ref="formRef" :model="form" label-position="right" label-width="96px">
        <el-card>
          <div :class="is1688 && !isLook && 'inline-block'" :style="{ width: is1688 && !isLook ? '60%' : null }">
            <div class="v-title mb-3">产品信息</div>
            <div class="flex items-center mb-3" v-if="!isLook && !is1688">
              <el-button type="primary" @click="addGoods(goodsRef)"><i class="dk-iconfont icon-Plus" />添加sku</el-button>
              <!-- <el-button :loading="loadings.split" @click="handleBatch('split')">拆分生成订单</el-button> -->
              <el-button @click="handleBatch('delete')"><i class="dk-iconfont icon-Delete" />删除产品</el-button>
              <div class="flex gap-2 ml-auto">
                <div>产品总数量: {{ total.purchase_num }}</div>
                <div>产品总额: ¥{{ total.total_price }}</div>
                <div>总运费: ¥{{ total.tracking_price }}</div>
                <div>总优惠: ¥{{ total.discount_price }}</div>
                <div>采购总成本: ¥{{ total.total_purchase_price }}</div>
              </div>
            </div>
            <vxe-table ref="tableRef" :data="form.sku" size="small" :row-config="{ height: 160 }" :column-config="{ resizable: true }" show-overflow>
              <vxe-column type="checkbox" width="40"></vxe-column>
              <vxe-column type="seq" width="50">
                <template #header>编号</template>
              </vxe-column>
              <vxe-column title="sku" :min-width="220">

                <template #default="{ row }">
                  <VText title="需求ID" :value="row.sku_no" />
                  <VText title="平台" :value="row.platform_name" />
                  <VText title="产品sku" :value="row.sku">
                    <span class='whitespace-nowrap'>{{row.sku}}</span>
                    <el-tag v-if="row.is_new === 2" type="success" effect="dark" class='mx-1'>新</el-tag>
                    <el-tag v-if="row.is_special_purchase === 2" type="danger" effect="dark">特</el-tag>
                  </VText>
                  <VText title="自定义sku" :value="row.custom_sku" />
                  <div class="flex items-center gap-2">
                    <el-link type='primary' @click="historyRef.open(row.sku)">
                      <i class="dk-iconfont icon-Tickets" />
                    </el-link>
                    <el-popover v-if="row.is_combination === 2" placement="right" :width="400">
                      <template #reference>
                        <el-button type="danger" circle size="small" class="scale-90"><span class="text-xs">组</span></el-button>
                      </template>
                      <el-table :data="row.combination_data" size="small">
                        <el-table-column property="origin_sku" label="组合SKU" />
                        <el-table-column property="sku" label="子SKU" />
                        <el-table-column property="sku_num" label="子SKU比例数" />
                      </el-table>
                    </el-popover>
                  </div>
                  <el-link type='primary' @click="to({
                    path: '/goods/task/product/edit',
                    query: {
                      spuId: row.spu_id,
                      type: 'view',
                    }
                  })">产品详情</el-link>
                  <div v-if="row.is_new_name">{{ row.is_new_name }}</div>
                  <VText title='是否退税' :value="row.is_refund_tax_name" />
                </template>
              </vxe-column>
              <vxe-column title="预计到货时间" :min-width="180">
                <template #header>
                  <div>预计到货时间</div>
                  <VGroup v-if="!isLook">
                    <el-date-picker v-model="tableForm.expect_delivery_time" placeholder="日期选择" type="date" value-format="YYYY-MM-DD" size="small" class="w-full" />
                    <el-button type="primary" size="small" @click="updateExpectDeliveryTime">批更</el-button>
                  </VGroup>
                </template>

                <template #default="{ row }">
                  <div class="flex flex-col gap-2">
                    <div class="flex items-center gap-1">
                      <el-input-number v-model="row.expect_delivery_num" :controls="false" :min="0" :step="1" :precision="0" placeholder="请输入" class="w-20"
                        @change="val => row.expect_delivery_time = addDays(val)" />天
                    </div>
                    <el-date-picker v-model="row.expect_delivery_time" placeholder="日期选择" type="date" value-format="YYYY-MM-DD" class="w-full" :disabled="isLook"
                      @change="val => timeChange(val, row)" />
                  </div>
                </template>
              </vxe-column>
              <vxe-column title="工厂可交货时间" field="factory_time" :min-width="100">
              </vxe-column>
              <vxe-column title="图片" :min-width="100">

                <template #default="{ row }">
                  <div class="flex items-center p-2">
                    <VImage :src="row.main_img" size="80px"></VImage>
                  </div>
                </template>
              </vxe-column>
              <vxe-column title="产品名称" :min-width="180">

                <template #default="{ row }">
                  <VText :value="row.sku_cn_title" :line="3" />
                </template>
              </vxe-column>
              <vxe-column title="产品属性" :min-width="110">
                <template #default="{ row }">
                  <VText title="长" :value="row.packing_size_cm_length+'cm'" />
                  <VText title="宽" :value="row.packing_size_cm_width+'cm'" />
                  <VText title="高" :value="row.packing_size_cm_height+'cm'" />
                  <VText title="毛重" :value="row.gross_weight_g+'g'" />
                  <VText title="体积" :value="(row.packing_size_m_volume || 0)+'m³'" />
                </template>
              </vxe-column>
              <vxe-column title="数量" :min-width="140">

                <template #header>
                  <div>数量</div>
                  <VGroup v-if="!isLook">
                    <el-input-number v-model="tableForm.purchase_num" :controls="false" clearable :min="0" :step="1" size="small" :precision="0" class="w-full" />
                    <el-button type="primary" size="small" @click="updatePurchaseNum">批更</el-button>
                  </VGroup>
                </template>

                <template #default="{ row }">
                  <el-input-number v-model="row.purchase_num" :controls="false" clearable :min="0" :step="1" :precision="0" class="w-full" :disabled="disabled && !is1688Edit"
                    @change="purchaseNumChange(row)" />
                </template>
              </vxe-column>

              <template v-if="!is_drawback">
                <vxe-column title="采购价格信息" :min-width="160">
                  <template #default="{ row }">
                    <div class="flex items-center gap-1">
                      <div v-if="form.basic.order_source === 3">
                        <div class="text-gray-500">采购未税报价:</div>
                        <el-input-number v-model="row.unit_price" :controls="false" :min="0" :step="0.01" :precision="2" placeholder="请输入" class="w-full"
                          @change="calcUnitPurchasePrice(row)" />
                      </div>
                      <VText v-else title="采购未税报价" :value="row.unit_price" />
                      <div v-if="row.compare">
                        <i v-if="row.compare === 1" class="dk-iconfont icon-Top text-red-600" />
                        <i v-else class="dk-iconfont icon-Bottom text-green-600" />
                      </div>
                    </div>
                  </template>
                </vxe-column>
              </template>

              <template v-else>
                <vxe-column title="采购价格信息" :min-width="160">
                  <template #default="{ row }">
                    <div class="flex items-center gap-1">
                      <VText title="采购未税报价" :value="row.unit_price" />
                      <div v-if="row.compare">
                        <i v-if="row.compare === 1" class="dk-iconfont icon-Top text-red-600" />
                        <i v-else class="dk-iconfont icon-Bottom text-green-600" />
                      </div>
                    </div>
                    <VText title="供应商税点" :value="row.tax_rate" />
                    <VText title="采购含税价" :value="row.unit_price_tax">
                      <div class="flex items-center gap-1">
                        <div>{{ row.unit_price_tax }}</div>
                        <div v-if="row.compare_tax">
                          <i v-if="row.compare_tax === 1" class="dk-iconfont icon-Top text-red-600" />
                          <i v-else class="dk-iconfont icon-Bottom text-green-600" />
                        </div>
                      </div>
                    </VText>
                  </template>
                </vxe-column>
              </template>
              <vxe-column title="报关信息" :min-width="180">
                <template #default="{ row }">
                  <VText title="报关名称" :value="row.customs_cn_name" />
                  <VText title="报关单位" :value="row.declare_unit" />
                  <VText title="报关编码" :value="row.customs_code" />
                </template>
              </vxe-column>
              <vxe-column title="运费分摊" :min-width="120">
                <template #header>
                  运费分摊 <el-tooltip class="box-item" effect="dark" placement="top">
                    <template #content>
                      1、总运费/产品重量比例/单个sku下单数量；<br>
                      2、可手动更改，但更改后的金额*下单数量要与总运费一致
                    </template>
                    <i class="dk-iconfont icon-QuestionFilled" />
                  </el-tooltip>
                </template>

                <template #default="{ row }">
                  <el-input-number v-model="row.tracking_price" :controls="false" clearable :min="0" :step="0.01" :precision="6" class="w-full" :disabled="disabled && !is1688Edit"
                    @blur="trackingChange(row)" />
                </template>
              </vxe-column>
              <vxe-column title="优惠分摊" :min-width="120">

                <template #default="{ row }">
                  <el-input-number v-model="row.discount_price" :controls="false" clearable :min="0" :step="0.01" :precision="6" class="w-full" :disabled="disabled && !is1688Edit"
                    @blur="discountChange(row)" />
                </template>
              </vxe-column>

              <template v-if="!is_drawback">
                <vxe-column title="单个采购成本" :min-width="120">
                  <template #default="{ row }">
                    {{ row.unit_purchase_price }}
                  </template>
                </vxe-column>
                <vxe-column title="产品总金额" :min-width="120">

                  <template #default="{ row }">
                    {{ row.is_drawback ? row.total_price_tax : row.total_price }}
                  </template>
                </vxe-column>
                <vxe-column title="采购总成本" :min-width="120">

                  <template #default="{ row }">
                    {{ row.is_drawback ? row.total_purchase_price_tax : row.total_purchase_price }}
                  </template>
                </vxe-column>
              </template>

              <template v-else>
                <vxe-column title="不含税产品总金额" :min-width="100">
                  <template #default="{ row }">
                    {{ toFixed(row.purchase_num * +row.unit_price) }}
                  </template>
                </vxe-column>
                <vxe-column title="含税产品总金额" :min-width="100">

                  <template #default="{ row }">
                    {{ toFixed(row.purchase_num * +row.unit_price_tax) }}
                  </template>
                </vxe-column>
              </template>
              <vxe-column title="来源信息" :min-width="180">
                <template #default="{ row }">
                  订单来源:
                  <div> <VSelect v-model="row.order_source" :options="options.order_source.filter(d => isCreateSku ? [4,9].includes(d.value) : true)" select placeholder="请选择" class="w-full" :disabled="!isCreateSku" /></div>
                  来源单号:
                  <div> <el-input v-model="row.source_no" placeholder="来源单号" class="w-full" :disabled="disabled" />
                  </div>
                </template>
              </vxe-column>
              <vxe-column title="产品链接" :min-width="140">
                <template #default="{ row }">
                  <el-link v-if="row.goods_link_type === 1" type='primary' :href="row.goods_link" target="_blank">
                    <div class="text-2-line">
                      <VText :value="row.goods_link" type="link" :line="2" />
                    </div>
                  </el-link>
                  <el-link v-else type='primary' class="text-red-600" @click="relevance(row)">
                    <i class="dk-iconfont icon-WarningFilled" />
                    未关联1688
                  </el-link>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <div class="h-full" :class="!isLook ? 'inline-block w-2/5 pl-3' : 'mt-3'" v-if="is1688">
            <div class="v-title mb-3">1688产品信息</div>
            <vxe-table ref="tableRef" :data="form.sku" size="small" :row-config="{ height: 160 }" :column-config="{ resizable: true }" show-overflow>
              <vxe-column title="图片" :min-width="100">
                <template #header>
                  <div class="h-[42px] leading-[42px]">图片</div>
                </template>
                <template #default="{ row }">
                  <div class="flex items-center p-2">
                    <VImage :src="row.ali_data.ali_main_image" size="80px"></VImage>
                  </div>
                </template>
              </vxe-column>
              <vxe-column title="产品名称" :min-width="180">

                <template #default="{ row }">
                  <VText :value="row.ali_data.subject" :line="3" />
                </template>
              </vxe-column>
              <vxe-column v-if="!form.basic.platform_order_no" title="产品属性" :min-width="240">

                <template #default="{ row }">
                  <div class="flex flex-col">
                    <VText v-if="!isLook" value="更新1688链接" type="link" class="mb-1"
                      @click="() => update1688LinkRef.open(row.ali_data.p_id ? row.ali_data : {goods_link: '', sku: row.sku})">
                    </VText>
                    <VSelect v-model="row.ali_data.seclected_sku_info" multiple collapse-tags filterable clearable :disabled="disabled" :options="aliOptions(row)" class="w-full"
                      @change="({ value }) => selectChange(value, row.ali_data)" />
                    <el-checkbox v-model="row.ali_data.is_update" :true-value="2" :false-value="1" :disabled="disabled">更新绑定属性</el-checkbox>
                  </div>
                </template>
              </vxe-column>
              <vxe-column title="平台下单数量" min-width="420">

                <template #default="{ row }">
                  <el-scrollbar max-height="130">
                    <VText title="起批量" :value="row.ali_data.ali_min_order_quantity" />
                    <div class="grid grid-cols-10 border border-b-0">
                      <div class="border-b p-1 col-span-2">属性</div>
                      <div class="border-b p-1 col-span-2">比例</div>
                      <div class="border-b p-1 col-span-3">1688下单数量</div>
                      <div class="border-b p-1 col-span-2">单价</div>
                      <div class="border-b p-1"></div>
                      <template v-if="row.ali_data.assoc_sku_info">
                        <div v-if="!row.ali_data.assoc_sku_info.length" class="col-span-full border-b p-1 text-center text-gray-400">无数据</div>
                        <template v-else>
                          <template v-for="(d, i) in row.ali_data.assoc_sku_info" :key="i">
                            <div class="border-b p-1 flex items-center col-span-2 w-full">
                              <VText :value="d.attribute_name" class="w-full" />
                            </div>
                            <div class="border-b p-1 flex items-center col-span-2">
                              <div v-if="form.basic.platform_order_no">{{ d.sku_num }}</div>
                              <el-input-number v-else v-model="d.sku_num" :controls="false" :min="0" :step="0.01" :precision="0" placeholder="请输入" class="w-full"
                                @change="skuNumChange(d, row.ali_data)" />
                            </div>
                            <div class="border-b p-1 flex items-center col-span-3">{{row.purchase_num * d.sku_num }}</div>
                            <div class="border-b p-1 flex items-center col-span-2">{{ toFixed(d.sku_price) }}
                            </div>
                            <div class="border-b p-1 flex items-center">
                              <el-button v-if="!form.basic.platform_order_no" link type="primary"
                                @click="row.ali_data.seclected_sku_info.splice(i, 1) && selectChange(row.ali_data.seclected_sku_info, row.ali_data)">移除</el-button>
                            </div>
                          </template>
                        </template>
                      </template>
                    </div>
                  </el-scrollbar>
                </template>
              </vxe-column>
              <vxe-column title="价格" :min-width="100">

                <template #default="{ row }">
                  <VText title="单价" :value="row.ali_unit_price" />
                  <VText title="合计" :value="row.ali_total_price" />
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </el-card>
        <div class="gap-x-2 mt-2" :style="{ display: isLook ? 'block' : 'grid', 'grid-template-columns': `repeat(${is1688 ? 4 : 3}, minmax(0, 1fr)) !important` }">
          <el-card class="mb-2">
            <div class="v-title mb-3">基础信息</div>
            <el-form-item label="采购单号" prop="purchase_no">
              <el-input v-if="!isCreate" v-model="form.basic.purchase_no" placeholder="请输入" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="供应商类型" prop="basic.purchase_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.basic.purchase_type" :options="options.purchase_type || []" placeholder="供应商类型" select filterable clearable :reserve-keyword="false"
                class="w-full" :disabled="form.basic.order_source !== 3" />
            </el-form-item>
            <el-form-item label="采购人员" prop="purchase_user_id">
              <VCascader v-model="form.basic.purchase_user_id" placeholder="请选择" filterable clearable disabled class="w-full" />
            </el-form-item>
            <el-form-item label="备货方式" prop="basic.prepare_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.basic.prepare_type" :options="options.prepare_type || []" placeholder="备货方式" select filterable clearable :reserve-keyword="false"
                class="w-full" :disabled="disabled && !is1688Edit" />
            </el-form-item>
            <el-form-item label="平台单号" prop="platform_order_no">
              <el-input v-if="!isCreate" v-model="form.basic.platform_order_no" placeholder="请输入" class="w-full" disabled />
            </el-form-item>
            <el-form-item label="目的仓库" prop="basic.destination_warehouse" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.basic.destination_warehouse" type="warehouse156" placeholder="目的仓库" select filterable clearable :reserve-keyword="false" class="w-full"
                :disabled="disabled && !is1688Edit" @change="warehouseChange" />
            </el-form-item>
            <el-form-item label="是否退税" prop="basic.is_drawback" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <el-radio-group v-model="form.basic.is_drawback" :disabled="disabled && !is1688Edit || form.basic.order_source === 3" @change="drawbackChange">
                <el-radio :value="2">含税</el-radio>
                <el-radio :value="1">不含税</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="物流单号" prop="tracking_data" class="leading-3 h-3">
              {{ isCreate ? '' : (form.basic.tracking_data || []).map(d => d.tracking_no).join(',') }}
            </el-form-item>
            <el-form-item label="业务状态" class="leading-4 h-4">
              {{ form.basic.audit_status_name || '待提交' }}
            </el-form-item>
            <el-form-item label="订单备注" prop="remark">
              <el-input v-model="form.basic.remark" placeholder="请输入" type="textarea" :disabled="disabled" :autosize="{ minRows: 2, maxRows: 5 }" />
            </el-form-item>
          </el-card>
          <el-card class="mb-2">
            <div class="v-title mb-3">供应商信息</div>
            <el-form-item label="供应商">
              <el-input v-model="form.supplier.supplier_name" placeholder="请输入" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="供应商类型">
              <el-input v-model="form.supplier.purchase_type_name" placeholder="请输入" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="结算方式">
              <el-input v-model="form.supplier.period_name" placeholder="请输入" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="结算时间">
              {{ form.supplier.settlement_time }}
            </el-form-item>
            <el-form-item label="付款起始日">
              {{ form.supplier.start_payment_time }}
            </el-form-item>
            <el-form-item label="交易方式">
              <el-input v-model="form.supplier.payment_type_name" placeholder="请输入" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="收款账号">
              <el-input v-model="form.supplier.collect_account" placeholder="请输入" :disabled="!isCreate" class="w-full" />
            </el-form-item>
            <el-form-item label="联系人" class="leading-4 h-4">
              {{ form.supplier.contact_name }}
            </el-form-item>
            <el-form-item label="联系方式" class="leading-4 h-4">
              {{ form.supplier.tel }}
            </el-form-item>
            <el-form-item label="供应商负责人" class="leading-4 h-4">
              {{ form.supplier.director_name }}
            </el-form-item>
            <el-form-item label="是否包邮">
              <v-group class="w-full">
                <VSelect v-model="form.supplier.free_shipping" :options="options.free_shipping || []" :disabled="disabled" placeholder="是否包邮" class="w-full" />
                <VSelect v-model="form.supplier.cod_type" :options="options.cod_type || []" :disabled="disabled" placeholder="是否到付" class="w-full" />
                <el-input-number v-if="form.supplier.free_shipping === 3" v-model="form.supplier.free_amount" :disabled="disabled" controls-position="right" :min="0" :step="0.01"
                  placeholder="金额（满金额包邮）" :precision="2" class="w-full" />
              </v-group>
            </el-form-item>
            <el-form-item label="供应商备注">
              <div class="w-full leading-5">
                <VText :value="form.supplier.supplier_remark" />
              </div>
            </el-form-item>
          </el-card>
          <el-card class="mb-2">
            <div class="v-title mb-3">结算信息</div>
            <el-form-item label="公司主体" prop="settlement.company_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.settlement.company_id" :options="options.company_id || []" placeholder="请选择" select filterable clearable :reserve-keyword="false"
                class="w-full" :disabled="disabled && !is1688Edit" />
            </el-form-item>
            <el-form-item label="结算币种" prop="currency">
              <VSelect v-model="form.settlement.currency" :options="options.currency || []" placeholder="请选择" select filterable clearable :reserve-keyword="false" class="w-full"
                :disabled="disabled && !is1688Edit" />
            </el-form-item>
            <el-form-item label="支付账号" prop="alipay_account">
              <VSelect v-model="form.settlement.alipay_account" :options="options.alipay_account || []" placeholder="请选择" select filterable clearable :reserve-keyword="false"
                class="w-full" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="财务状态" prop="purchase_no">
              {{ form.settlement.finance_status_name || '待申请付款' }}
            </el-form-item>
            <el-form-item label="付款单号" prop="purchase_no">
              {{ (form.settlement.payment_no || []).join(',') }}
            </el-form-item>
            <el-form-item label="产品总额" prop="purchase_no">
              {{ total.total_price }}
            </el-form-item>
            <el-form-item label="总运费" prop="tracking_price">
              <el-input-number v-model="form.settlement.tracking_price" :controls="false" :min="0" :step="0.01" :precision="2" class="w-full" :disabled="disabled && !is1688Edit"
                @change="updateTracking" />
            </el-form-item>
            <el-form-item label="总优惠" prop="discount_price">
              <el-input-number v-model="form.settlement.discount_price" :controls="false" :min="0" :step="0.01" :precision="2" class="w-full" :disabled="disabled && !is1688Edit"
                @change="updateDiscount" />
            </el-form-item>
            <el-form-item label="应付金额" prop="purchase_no">
              {{ total.total_purchase_price }}
            </el-form-item>
          </el-card>
          <el-card v-if="is1688 && form.platform" class="mb-2">
            <div class="v-title mb-3 flex items-center gap-3">
              1688下单核算
              <a v-if="form.basic.platform_order_no" target="_blank"
                :href="`https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?touid=cnalichn${form.platform.seller_id}`">
                <img border="0" src="https://xc2k-pms.oss-cn-shenzhen.aliyuncs.com/icon/wangwang.gif" alt="联系卖家" title="联系卖家">
              </a>
            </div>
            <el-form-item label="买家留言" prop="settlement.company_id">
              <el-input v-model="form.platform.message" placeholder="请输入" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
                :disabled="disabled || form.basic.platform_order_no !== '' && !is1688Edit" />
            </el-form-item>
            <el-form-item label="当前账号名称" prop="currency" class="leading-3 h-3">
              {{ form.platform.purchase_account }}
            </el-form-item>
            <el-form-item label="收货信息" prop="alipay_account">

              <template #label>
                <div class="font-bold text-right">
                  收货信息
                  <el-button v-if="!isLook && form.basic.platform_order_no === '' && is1688Edit" link type="primary" @click="getAddress"><i class="dk-iconfont icon-RefreshRight" />获取</el-button>
                </div>
              </template>
              <div class="flex flex-col gap-1">
                <div class="flex gap-1">
                  <el-input v-model="form.platform.deliver_data.full_name" placeholder="收货人" :disabled="disabled || form.basic.platform_order_no !== '' && !is1688Edit"
                    class="w-full" />
                  <el-input v-model="form.platform.deliver_data.mobile" placeholder="手机号" :disabled="disabled || form.basic.platform_order_no !== '' && !is1688Edit"
                    class="w-full" />
                </div>
                <Area v-model="form.platform.deliver_data" wrap class="w-full" :disabled="disabled || form.basic.platform_order_no !== '' && !is1688Edit" />
                <el-input v-model="form.platform.deliver_data.post" placeholder="邮编" :disabled="disabled || form.basic.platform_order_no !== '' && !is1688Edit" class="w-full" />
              </div>
            </el-form-item>
            <el-form-item label="交易方式" prop="platform.trade_type" :rules="[{ message: '不能为空', trigger: 'blur' }]">

              <template #label>
                <div class="font-bold text-right">
                  <span class="text-red-600">*</span>
                  交易方式
                  <el-button v-if="!isLook && form.basic.platform_order_no === '' && is1688Edit" link type="primary" @click="getPaymentType"><i class="dk-iconfont icon-RefreshRight" />获取</el-button>
                </div>
              </template>
              <el-radio-group v-model="form.platform.trade_type" :disabled="disabled || form.basic.platform_order_no !== '' && !is1688Edit">
                <el-radio v-for="(d, i) in form.platform.trade_types || []" :key="i" :value="d.value">{{ d.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否使用红包" prop="platform.is_use_coupon" class="mt-[35px]">
              <template #label>
                <div class="font-bold text-right">是否使用红包</div>
              </template>
              <el-radio-group v-model="form.platform.is_use_coupon" :disabled="disabled || form.basic.platform_order_no !== '' && !is1688Edit">
                <el-radio v-for="(d, i) in [{label:'否',value:1},{label:'是',value:2}]" :key="i" :value="d.value">{{ d.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="form.basic.platform_order_no">
              <el-form-item label="平台下单数量" class="leading-3 h-3">
                {{ form.platform.platform_purchase_num }}
              </el-form-item>
              <el-form-item label="平台运费" class="leading-3 h-3">
                {{ form.platform.platform_tracking_price }}
              </el-form-item>
              <el-form-item label="平台优惠" class="leading-3 h-3">
                {{ form.platform.platform_discount_price }}
              </el-form-item>
              <el-form-item label="当前订单总额" class="leading-3 h-3">
                {{ form.platform.platform_total_price }}
              </el-form-item>
            </template>
          </el-card>
        </div>

        <template v-if="isLook">
          <el-card class="mb-2">
            <div class="v-title my-3">日志信息</div>
            <vxe-table :data="form.log" size="small">
              <vxe-column title="操作人" field="create_user"></vxe-column>
              <vxe-column title="操作类型" field="log_type"></vxe-column>
              <vxe-column title="详情" field="log_info" min-width="300"></vxe-column>
              <vxe-column title="操作时间" field="create_time"></vxe-column>
            </vxe-table>
          </el-card>
        </template>
      </el-form>
    </div>

    <template #footer>
      <template v-if="isLook">
        <el-button @click="toBack()">返 回</el-button>
      </template>

      <template v-else>
        <el-button @click="toBack()">返 回</el-button>
        <template v-if="is1688">
          <el-button type="primary" :loading="loadings['create' + 2]" @click="create(2)">保 存</el-button>
          <el-button v-if="form.basic.platform_order_no === '' && is1688" type="primary" :loading="loadings['create1688' + 2]" @click="create1688(2)">下单到1688</el-button>
        </template>

        <template v-else>
          <el-button type="primary" :loading="loadings['create' + 2]" @click="create(2)">保 存</el-button>
        </template>
        <VButton v-if="!isCreate" auth="/purchase/manage/process/edit/submit" type="primary" :loading="loadings['create' + 1]" @click="create(1)">保存并提交</VButton>
        <VButton auth="/purchase/manage/process/batch_cancellation" @click="cancelRef.open([form.basic.p_id])">作废</VButton>
      </template>
    </template>
    <Goods ref="goodsRef" @change="goodsChange" />
    <VHistory ref="historyRef" />
    <Relevance ref="relevanceRef" @success="relevanceSuccess" />
    <Update1688Link ref="update1688LinkRef" />
    <Cancel ref="cancelRef" :options="options" @success="toBack(true)" />
  </v-page>
</template>

<script setup name="1688,create,edit,view" lang="jsx">
import api from './api'
import { ElMessage,ElMessageBox } from 'element-plus'
import Goods from '@/components/Goods'
import VHistory from '@/components/VHistory'
import Area from '@/components/Area'
import Anchors from '@/components/Anchors'
import XEUtils from 'xe-utils'
import Relevance from '@/views/product/product/components/Relevance'
import Update1688Link from './Update1688Link'
import { getOption } from '@/api/public'
import { computed } from 'vue'
import { to, closeTab } from '@/utils/action'
import { resMessage } from '@/utils/res'
import Cancel from '../components/Cancel'

const route = useRoute()
const router = useRouter()
const toBack = (query) => {
  // 跳转到上一个路由
  const prevPath = `PREV_ROUTER:${route.path}`
  router.push(sessionStorage.getItem(prevPath))
  sessionStorage.removeItem(prevPath)
  if (query) {
    sessionStorage.setItem('DK_VUI_TABLE_QUERY', true)
  }
  closeTab()
}
const props = defineProps({
  id: { type: String, default: '182' },
})
const emit = defineEmits(['close', 'success'])

const aliOptions = row => (row.ali_data.ali_sku_info || []).map(d => ({ label: '' + d.attribute_name, value: d.sku_id }))

// 获取options
const options = ref({})
const baseName = 'purchase'
Promise.all([
  getOption({ type: 'supplier' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: 'test', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

const getPaymentType = () => {
  api.getPaymentType(form.value).then(res => {
    form.value.platform.trade_types = res.data
    for (const d of ['period', 'creditBuy', 'assureTrade', res.data[0]?.value || '']) {
      if(res.data.find(da => da.value === d)) {
        form.value.platform.trade_type = d
        break
      }
    }
  })
}
const cancelRef = ref()
const load = ref(false)
let loadings = reactive({})
// 表单处理
const formRef = ref()
const tableRef = ref()
const update1688LinkRef = ref()
const form = ref({
  basic: {},
  supplier: {},
  settlement: {},
  total: {},
  platform: { deliver_data: {} },
  sku: [],
  log: [],
})
const tableForm = ref({})

const maps = import.meta.env.VITE_APP_ENV === 'staging' ?
  {
    '176,177,180': {
      'is_drawback': 2,
      'company_id': 3
    },
    '178,179': {
      'is_drawback': 2,
      'company_id': 1
    },
    '1032': {
      'is_drawback': 2,
      'company_id': 5
    },
    '1033': {
      'is_drawback': 2,
      'company_id': 5
    },
    '': {
      'is_drawback': 1,
      'company_id': 2
    }
  } :
  {
    '4,5,8': {
      'is_drawback': 2,
      'company_id': 3
    },
    '6,7': {
      'is_drawback': 2,
      'company_id': 1
    },
    '1113': {
      'is_drawback': 2,
      'company_id': 5
    },
    '1112': {
      'is_drawback': 2,
      'company_id': 5
    },
    '': {
      'is_drawback': 1,
      'company_id': 2
    }
  }
const warehouseChange = ({ option }) => {
  const { value } = option
  for (const [key, values] of Object.entries(maps)) {
    const keys = key.split(',').map(d => +d)
    if (keys.includes(value) || !key) {
      form.value.basic.is_drawback = values.is_drawback
      form.value.settlement.company_id = values.company_id
      break
    }
  }
}


const toFixed = (val, num = 2) => XEUtils.round(val, num)

const isLook = computed(() => route.path.indexOf('/manage/process/view') > -1)
const isCreate = computed(() => route.path.indexOf('/manage/process/create') > -1)
const isCreateSku = computed(() => route.path.indexOf('/manage/process/create/sku:') > -1)
const is1688 = computed(() => route.path.indexOf('/manage/process/1688') > -1 || route.path.indexOf('/manage/process/view/1688') > -1)
const is1688Edit = computed(() => route.path.indexOf('/manage/process/1688') > -1)

// 是否退税联动收款账号
const getSupplier = (is_drawback) => {
  api.getSupplier({ is_drawback, supplier_id: form.value.supplier.supplier_id }).then(res => {
    form.value.supplier.collect_account = res.data.collect_account
  })
}
const drawbackChange = (is_drawback) => {
  if (isCreate.value) {
    getSupplier(is_drawback)
  }
}

// 1688产品属性
const update1688_link = async () => {
  const detail = await api.detail1688({ p_ids: [d.p_id] })
  const { ali_main_image, ali_min_order_quantity, subject, ali_sku_info, assoc_sku_info, seclected_sku_info } = detail.data
  d = Object.assign(d, { ali_main_image, ali_min_order_quantity, subject, ali_sku_info, assoc_sku_info, seclected_sku_info })
}

const selectChange = (val, row) => {
  const { ali_price_ranges, assoc_sku_info, ali_sku_info } = row
  row.assoc_sku_info = row.assoc_sku_info.filter(d => val.includes(d.sku_id))
  val.forEach(v => {
    if (assoc_sku_info.some(d => d.sku_id === v)) return
    const item = {
      ...ali_sku_info.find(d => d.sku_id === v) || {},
      sku_num: row.ali_min_order_quantity,
      product_id: row.product_id
    }
    if (ali_price_ranges.length > 1) {
      item.sku_price = ali_price_ranges[0]?.price
    }
    row.assoc_sku_info.push(item)
  })
}

const skuNumChange = (item, row) => {
  const { ali_price_ranges } = row
  if (ali_price_ranges.length < 2) {
    return
  }
  const allNum = row.assoc_sku_info.reduce((acc, cur) => acc += (+cur.sku_num || 0), 0)
  const { price } = ali_price_ranges.findLast(d => allNum >= d.startQuantity) || ali_price_ranges[0] || { price: 0 }
  row.assoc_sku_info.forEach(d => {
    d.sku_price = price
  })
}

// 初始化
const init = async () => {
  if (!isCreate.value) {
    const params = { p_id: props.id.replace('1688:', '') }
    if (route.path.indexOf('/manage/process/1688') > -1 || route.path.indexOf('/manage/process/view/1688') > -1) {
      params.type = 'order'
    }
    const res = await api.detail(params)
    if (route.path.indexOf('/manage/process/1688') > -1) {
      const message = `PO号：${res.data.basic.purchase_no}，${res.data.sku.map(d => `SKU：${d.sku}，数量：${d.purchase_num}套，国家：${res.data.basic.country_name}，产品名：${d.sku_cn_title}；\n`).join(' ')}`
      res.data.platform.message = message +
        `
外箱标识卡内容包括:PO号/SKU/ 箱内数量;拒收无外箱标识卡及到付件，单箱重量不能超过：15KG,不能混箱，外箱必须要贴外箱标识卡`
    }
    res.data.sku.forEach(d => {
      d.expect_delivery_num = daysBetween(d.expect_delivery_time)
      return d
    })
    form.value = res.data
    if(is1688.value && form.value.platform){
     const {is_use_coupon} = res.data?.platform||{}
     const {purchase_type} = res.data?.basic||{}
     const coupon = {1:2,2:1,4:1}
     form.value.platform.is_use_coupon = is_use_coupon?is_use_coupon:coupon[purchase_type]
    }
    if(!params?.type) return
    updateTracking()
    updateDiscount()
  } else {
    const { userInfo } = window
    let res = null
    if (route.path.indexOf('/manage/process/create/sku:') > -1) {
      res = await api.getSku({ sku: props.id.replace('sku:', '').split('__').map(d => d) })
    } else {
      res = await api.getDetail({ pdcs_ids: props.id.split(',').map(d => +d) })
    }
    const { product, supplier } = res.data
    form.value.sku = product.map(d => {
      d.unit_purchase_price = +d.unit_price
      d.unit_purchase_price_tax = +d.unit_price_tax
      d.total_purchase_price = toFixed(+d.unit_price * d.purchase_num)
      d.total_purchase_price_tax = toFixed(+d.unit_price_tax * d.purchase_num)
      d.total_price = toFixed(+d.unit_price * d.purchase_num)
      d.total_price_tax = toFixed(+d.unit_price_tax * d.purchase_num)
      d.tracking_price = 0
      d.discount_price = 0
      d.expect_delivery_num = daysBetween(d.expect_delivery_time)
      return d
    })
    const countrys = [...new Set(product.map(d => d.country))]
    const isAllUS = countrys.length === 1 && countrys[0] === 'US'
    const isHJ = product[0].department_id === (import.meta.env.VITE_APP_ENV === 'staging' ? 35 : 35)
    form.value.supplier = supplier
    form.value.basic = {
      is_drawback: 2,
      purchase_type: supplier.purchase_type,
      purchase_user_id: userInfo?.user?.user_id,
      purchase_user_name: userInfo?.user?.en_name,
      prepare_type: isAllUS && isHJ ? 2 : 1
    }
    form.value.settlement.currency = 'CNY'
    getSupplier(2)
  }
  load.value = true
}
init()

const disabled = computed(() => Boolean(isLook.value))

const is_drawback = computed(() => form.value.basic?.is_drawback === 2)
const total = computed(() => {
  const { purchase_num, total_price, tracking_price, discount_price } = (form.value.sku || []).reduce((acc, cur) => {
    acc.purchase_num += +(cur.purchase_num || 0)
    acc.total_price = toFixed(+acc.total_price + (is_drawback.value ? +cur.total_price_tax : +cur.total_price))
    acc.tracking_price = toFixed(+acc.tracking_price + (+(cur.tracking_price || 0) * +cur.purchase_num), 6)
    acc.discount_price = toFixed(+acc.discount_price + (+(cur.discount_price || 0) * +cur.purchase_num), 6)
    return acc
  }, { purchase_num: 0, total_price: 0, tracking_price: 0, discount_price: 0 })
  const total_purchase_price = toFixed(+total_price + +tracking_price - +discount_price)
  const formatted_tracking_price = toFixed(+tracking_price, 2)
  const formatted_discount_price = toFixed(+discount_price, 2)
  return { purchase_num, total_price, tracking_price:formatted_tracking_price, discount_price:formatted_discount_price, total_purchase_price }
})

// 关联1688
const relevanceRef = ref()
const relevance = (row) => {
  relevanceRef?.value.open(row.p_id)
}

const relevanceSuccess = item => {
  form.value.sku.forEach(d => {
    if (d.p_id === item.p_id) {
      d.goods_link = item.goods_link
      d.goods_link_type = item.goods_link_type
    }
  })
}

// 获取1688收货地址
const getAddress = () => {
  const { purchase_user_id } = form.value.basic
  api.address({ purchase_user_id }).then(res => {
    form.value.platform.deliver_data = res.data
    ElMessage.success('获取成功')
  })
}

// 批量操作
const handleBatch = (name) => {
  const table = tableRef?.value
  const selection = table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const handle = {
    split: async () => {
      if (selection.some(d => !d.ps_id)) {
        ElMessage.warning('请选择采购单已存在的sku')
        return
      }
      loadings.split = true
      api.split({ p_id: form.value.basic.p_id, sku: selection }).then(res => {
        table?.remove(selection)
        ElMessage.success('操作成功')
      }).finally(() => {
        loadings.split = false
      })
    },
    delete: () => {
      table?.remove(selection)
      const { fullData } = table?.getTableData()
      form.value.sku = fullData
    }
  }
  handle[name]()
}


// 批量更改数量
const updatePurchaseNum = () => {
  form.value.sku.forEach(d => {
    d.purchase_num = tableForm.value.purchase_num
    calcUnitPurchasePrice(d)
  })
  // tableForm.value.purchase_num = undefined
}

// 批量更改时间
const updateExpectDeliveryTime = () => {
  form.value.sku.forEach(d => {
    d.expect_delivery_time = tableForm.value.expect_delivery_time
    d.expect_delivery_num = daysBetween(d.expect_delivery_time)
  })
  // tableForm.value.purchase_num = undefined
}

// 计算单个成本
const calcUnitPurchasePrice = async (row) => {
  // updateTracking()
  // updateDiscount()
  await 1
  row.unit_purchase_price = toFixed(row.unit_price + row.tracking_price - row.discount_price, 6)
  row.unit_purchase_price_tax = toFixed(row.unit_price_tax + row.tracking_price - row.discount_price, 6)
  row.total_purchase_price = toFixed(row.unit_purchase_price * row.purchase_num)
  row.total_purchase_price_tax = toFixed(row.unit_purchase_price_tax * row.purchase_num)
  row.total_price = toFixed(row.unit_price * row.purchase_num)
  row.total_price_tax = toFixed(row.unit_price_tax * row.purchase_num)
  form.value.sku = [...form.value.sku]
}

const purchaseNumChange = () => {
  updateTracking()
  updateDiscount()
}

// 更新总运费
const trackingChange = async (row) => {
  calcUnitPurchasePrice(row)
  await 1
  form.value.settlement.tracking_price = total.value.tracking_price
}

// 更新总优惠
const discountChange = async (row) => {
  calcUnitPurchasePrice(row)
  await 1
  form.value.settlement.discount_price = total.value.discount_price
}

/**运费 */
// 分摊运费
const updateTracking = async (value = +form.value.settlement.tracking_price) => {
  const { settlement, sku } = form.value
  const { tracking_price } = settlement
  const all = form.value.sku.reduce((acc, cur) => acc += Math.max(cur.gross_weight_g || 0, cur.volume_g || 0), 0)
  form.value.sku.forEach(d => {
    const ratio = toFixed(Math.max(d.gross_weight_g || 0, d.volume_g || 0) / all, 6)
    const price = toFixed(tracking_price * ratio, 6)
    d.tracking_price = toFixed(price / d.purchase_num, 6)
    calcUnitPurchasePrice(d)
  })
  // 修复浮点数
  await 1
  const offset = toFixed(+total.value.tracking_price - value)
  if (offset) {
    const item = form.value.sku[0]
    const ratio = toFixed(Math.max(item.gross_weight_g || 0, item.volume_g || 0) / all, 6)
    const price = toFixed(tracking_price * ratio, 6)
    item.tracking_price = toFixed((price - offset) / item.purchase_num, 6)
    calcUnitPurchasePrice(item)
  }
}
/**优惠 */
// 分摊优惠
const updateDiscount = async (value = +form.value.settlement.discount_price) => {
  const { settlement, sku } = form.value
  const { discount_price } = settlement
   const all = form.value.sku.reduce((acc, cur) => acc += Math.max(cur.gross_weight_g || 0, cur.volume_g || 0), 0)
  form.value.sku.forEach(d => {
    const ratio = toFixed(Math.max(d.gross_weight_g || 0, d.volume_g || 0) / all, 6)
    const price = toFixed(discount_price * ratio, 6)
    d.discount_price = toFixed(price / d.purchase_num, 6)
    calcUnitPurchasePrice(d)
  })
  // 修复浮点数
  await 1
  const offset = toFixed(+total.value.discount_price - value)
  if (offset) {
    const item = form.value.sku[0]
    const ratio = toFixed(Math.max(item.gross_weight_g || 0, item.volume_g || 0) / all, 6)
    const price = toFixed(tracking_price * ratio, 6)
    item.discount_price = toFixed((price - offset) / item.purchase_num, 6)
    calcUnitPurchasePrice(item)
  }
}

// 商品
const goodsRef = ref()
const addGoods = (goodsRef) => {
  goodsRef.open()
}
const goodsChange = (val) => {
  const { sku } = form.value
  const checkeds = val.filter(d => !sku.some(s => s.p_id === d.p_id)).map(d => {
    d.tracking_price = 0
    d.discount_price = 0
    d.order_source = 4
    d.unit_purchase_price = d.unit_price
    return d
  })
  form.value.sku.unshift(...checkeds)
}

// 历史下单价格
const historyRef = ref()

const makeData = () => {
  for (const key in total.value) {
    const value = total[key]
    form.value.settlement[key] = value
  }
  form.value.settlement.purchase_num = form.value.basic.purchase_num = total.value.purchase_num
  form.value.settlement.discount_price = total.value.discount_price
  form.value.settlement.tracking_price = total.value.tracking_price
  form.value.settlement.total_price = form.value.settlement.total_price_tax = total.value.total_price
  form.value.settlement.total_purchase_price = form.value.settlement.total_purchase_price_tax = total.value.total_purchase_price
}
const submitFn = async (p_ids, success) => {
      const res = await api.submit({ p_ids, submit_status: 0, is_skip: 1 })
      const submit = async (p_ids, submit_status, is_skip) => {
        ElMessageBox.close()
        const r = await api.submit({ p_ids, submit_status, is_skip })
        resMsg(r)
      }
      const resMsg = (res) => {
        resMessage({
          res,
          successText: '符合',
          errorText: '不符合',
          handle: () => {
            const ids = res.data.data
            return <div class='flex mt-2'>
              <el-button class='ml-auto' onClick={() => ElMessageBox.close()}>取消</el-button>
              {res.data.is_skip === 2 ? <el-button type='primary' onClick={() => submit(p_ids, 0, 2)}>继续提交</el-button> : ''}
              {res.data.is_skip !== 2 && ids.length ? <el-button type='primary' onClick={() => submit(ids, 1, 1)}>继续提交</el-button> : ''}
              {res.data.is_skip !== 2 && ids.length ? <el-button type='primary' onClick={() => submit(ids, 2, 1)}>更新供应商信息</el-button> : ''}
            </div>
          },
          success
        })
      }
      resMsg(res)
    }
// 提交
const create = async (is_submit) => {
  const validator = await formRef?.value.validate()
  if (!validator) return
  makeData()
  form.value.basic.is_submit = 2
  if (isCreate.value) {
    form.value.sku.forEach(d => {
      calcUnitPurchasePrice(d)
    })
  }
  loadings['create' + is_submit] = true
  await 1
  api[isCreate.value ? 'create' : 'edit'](form.value).then(res => {
    if(is_submit === 1) {
      submitFn([form.value.basic.p_id], () => {
        ElMessage.success('保存成功')
        emit('success')
        toBack(true)
      })
    } else {
      ElMessage.success('保存成功')
      emit('success')
      toBack(true)
    }
  }).finally(() => {
    loadings['create' + is_submit] = false
  })
}
const create1688 = async (is_submit) => {
  const validator = await formRef?.value.validate()
  if (!validator) return
  makeData()
  form.value.basic.is_submit = is_submit
  form.value.sku.forEach(d => {
    d.ali_data.goods_link_type = d.ali_data.subject ? 1 : 2
  })
  loadings['create1688' + is_submit] = true
  api.order(form.value).then(res => {
    ElMessage.success('下单成功')
    emit('success')
    toBack(true)
  }).finally(() => {
    loadings['create1688' + is_submit] = false
  })
}

const timeChange = (val, row) => {
  row.expect_delivery_num = daysBetween(val)
  const time = new Date(val)
  time.setDate(time.getDate() - row.transport_day - row.storage_day - row.inspection_time)
  row.origin_factory_time = row.factory_time = XEUtils.toDateString(time, 'yyyy-MM-dd')
}

// 计算两个日期相差多少天
const daysBetween = (end, start = Date.now()) => {
  const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
  const firstTime = new Date(start).getTime(); // 第一个时间的毫秒数
  const secondTime = new Date(end).getTime(); // 第二个时间的毫秒数
  return Math.round((secondTime - firstTime) / oneDay);
}

const addDays = (daysToAdd) => {
  const currentDate = new Date(); // 获取当前日期和时间
  currentDate.setDate(currentDate.getDate() + daysToAdd); // 设置新的日期
  return XEUtils.toDateString(currentDate, 'yyyy-MM-dd')
}
</script>